package com.knowledgeBase.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;

/**
 * @author liangyonghao
 * @date 2022年06月27日上午 8:59
 */
@Service
public class MailController {
    private final JavaMailSender mailSender;
    private JavaMailSenderImpl javaMailSender;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${spring.mail.username}")
    private String username;

    public MailController(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendTextMail() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo("l2785445847@163.com");
        mailMessage.setSubject("测试");
        mailMessage.setText("测试内容");
        mailMessage.setFrom(username);
        mailSender.send(mailMessage);
    }

    public void sendHTMLMail(String content) throws MessagingException {
        logger.info("xxxx");
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setTo("l2785445847@163.com");
        helper.setSubject("测试发送html");
        helper.setText(content, true);
        helper.setFrom(username);
        mailSender.send(helper.getMimeMessage());
    }

    public void sendAttachmentsMail(String filePath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(username);
        helper.setTo("l2785445847@163.com");
        helper.setSubject("测试发送附件");
        helper.setText("测试", true);
        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = file.getFilename();
        helper.addAttachment(fileName, file);
        mailSender.send(helper.getMimeMessage());
    }

    public void emailDynamic(){
        //动态配置自定义发送邮件
        javaMailSender.setHost("");
//        javaMailSender.setPort("");
        javaMailSender.setUsername("");
        javaMailSender.setPassword("");
        javaMailSender.setDefaultEncoding("UTF-8");
        Properties p =new Properties();
        p.setProperty("xx","true");

    }
}
